package pt.fct.mpc.lastfm.album;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import pt.fct.mpc.lastfm.R;
import pt.fct.mpc.lastfm.artist.ArtistActivity;
import pt.fct.mpc.lastfm.connectivity.LastfmBluetoothUnavailableException;
import pt.fct.mpc.lastfm.connectivity.LastfmURL;
import pt.fct.mpc.lastfm.generic.ImageActivity;
import pt.fct.mpc.lastfm.generic.TextActivity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

public class AlbumInfoActivity extends Activity {

	private static final String TAG = "Last.fm Album Activity";
	AlbumData albumDataSet;
	boolean gotAlbum = false;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.album_info);
		
		// Reads the info sent by the intent
		Intent the_intent_that_gave_life_to_everything = getIntent();
		Bundle intent_data = the_intent_that_gave_life_to_everything
				.getExtras();

		if (intent_data == null) {
			finish();
		}

		albumDataSet = (AlbumData) intent_data.getSerializable("albumserial");

		if (albumDataSet == null) {
			Log.e(TAG, "Null values from bundle: albumDataSet = "
					+ albumDataSet);
			finish();
		}

		if (!gotAlbum)
			getAlbumInfo();
		
		createAlbumInfoTab();
	}

	private void getAlbumInfo() {
		String album_artist;
		String album_name;
	
		try {
			album_artist = URLEncoder.encode(albumDataSet.getArtist(), "UTF-8");
			album_name = URLEncoder.encode(albumDataSet.getName(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw new RuntimeException("encoding problems");
		}
	
		String search_query = "?method=album.getinfo" + "&artist="
				+ album_artist + "&album=" + album_name + "&api_key="
				+ getString(R.string.lastfm_api_key);

		String request_str = getString(R.string.lastfm_api_url) + search_query;

		LastfmURL request_url = null;
		try {
			request_url = new LastfmURL(request_str);
		} catch (MalformedURLException e3) {
			Log.d("ArtistActivity.getArtistInfo", "MalformedURLException 143");
		}

		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser sp = null;
		try {
			sp = spf.newSAXParser();
		} catch (ParserConfigurationException e2) {
			Log.d("AlbumActivity.getAlbumInfo",
					"ParserConfigurationException 151");
		} catch (SAXException e2) {
			Log.d("AlbumActivity.getAlbumInfo", "SAXException 153");
		}

		XMLReader xr = null;
		try {
			xr = sp.getXMLReader();
		} catch (SAXException e1) {
			Log.d("AlbumActivity.getAlbumInfo", "SAXException 160");
		}

		AlbumXmlHandler myAlbumXmlHandler = new AlbumXmlHandler();
		xr.setContentHandler(myAlbumXmlHandler);

		try {
			xr.parse(new InputSource(request_url.openStream()));
		} catch (IOException e) {
			Log.d("ArtistActivity.getArtistInfo", "IOException 169");
		} catch (SAXException e) {
			Log.d("ArtistActivity.getArtistInfo", "SAXException 171");
		} catch (LastfmBluetoothUnavailableException e) {
			e.printStackTrace();
		}

		albumDataSet.setAlbumInfo(myAlbumXmlHandler.getParsedData());
		this.gotAlbum = true;
	}

	private void createAlbumInfoTab() {
		ImageView imageView = (ImageView) findViewById(R.id.cover);
		
		String album_image_str = getAlbumImage(albumDataSet);
		if ((album_image_str != null) && (album_image_str.length() > 0))
			imageView.setImageBitmap(urlToImage(album_image_str));

		TextView albumArtistView = (TextView) findViewById(R.id.album_artist);
		albumArtistView.setText(albumDataSet.getArtist());

		TextView albumNameView = (TextView) findViewById(R.id.album_name);
		albumNameView.setText(albumDataSet.getName());
		
		TextView albumReleaseDate = 
			(TextView) findViewById(R.id.album_release_date);
		String album_release_date = albumDataSet.getRelease_date();
		if (album_release_date != null)
		{
			String[] release_date_fields = album_release_date.split(",");
			Log.d(TAG, "release_date_fields = "+release_date_fields);
			if (release_date_fields.length > 0)
			{
				Log.d(TAG, "Setting release date");
				albumReleaseDate.setText(release_date_fields[0]);
			}
		}
			
		

		TextView albumSummaryView = (TextView) findViewById(R.id.album_summary);
		String album_summary = Html.fromHtml(albumDataSet.getSummary())
				.toString();

		if ((album_summary == null) || (album_summary.length() <= 0))
			album_summary = "No album summary available";

		String album_info_content = albumDataSet.getContent();
		String show_more = "";
		if ((album_info_content != null) && (album_info_content.length() > 0))
			show_more = "Full Information Available...";

		albumSummaryView.setText("Summary: \n" + album_summary + show_more);

		TextView albumTagsView = (TextView) findViewById(R.id.album_tags);
		List<String> listTags = albumDataSet.getTags();
		String tags = "";
		if ((listTags != null) && (listTags.size() > 0)) {
			tags = "Tags: " + listTags.get(0);
			for (int i = 1; i < listTags.size(); i++)
				tags += ", " + listTags.get(i);
		}
		if (tags.length() == 0)
			tags = "No tags available";
		albumTagsView.setText(tags);

		imageView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String imgUrl = albumDataSet.getImage_extralarge();
				if (imgUrl == "") {
					imgUrl = albumDataSet.getImage_large();
					if (imgUrl == "") {
						imgUrl = albumDataSet.getImage_medium();
						if (imgUrl == "") {
							imgUrl = albumDataSet.getImage_small();
							if (imgUrl == "")
								return;
						}
					}
				}

				Bundle intent_data = new Bundle();
				intent_data.putString("url", imgUrl);

				Intent intent = new Intent(getApplicationContext(),
						ImageActivity.class);
				intent.putExtras(intent_data);
				startActivity(intent);
			}
		});

		albumSummaryView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String text = albumDataSet.getContent();

				if ((text == null) || (text.length() <= 0))
					return;
				
				if (!albumDataSet.isContentParsed()) {
					String[] textArr = text.split("\n");
					text = "";
					for (int i = 0; i < textArr.length; i++)
						text += "	" + Html.fromHtml(textArr[i]).toString()
								+ "\n";
					albumDataSet.setContent(text);
					albumDataSet.setContentParsed(true);
				}

				Bundle intent_data = new Bundle();
				intent_data.putString("text", text);

				Intent intent = new Intent(getApplicationContext(),
						TextActivity.class);
				intent.putExtras(intent_data);
				startActivity(intent);
			}
		});

		albumArtistView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String text = albumDataSet.getArtist();
				Bundle intent_data = new Bundle();
				intent_data.putString("name", text);

				Intent intent = new Intent(getApplicationContext(),
						ArtistActivity.class);
				intent.putExtras(intent_data);
				startActivity(intent);
			}
		});
	}

	private String getAlbumImage(AlbumData albumDataSet)
	{
		String default_image = albumDataSet.getImage_large();
		
		if (default_image == null)
		{
			String tmp = null;
			do
			{
				 tmp = albumDataSet.getImage_medium();
				 if (tmp != null)
					 break;
				 
				 tmp = albumDataSet.getImage_extralarge();
				 if (tmp != null)
					 break;
				 
				 tmp = albumDataSet.getImage_small();
				 if (tmp != null)
					 break;

			} while (false);
			
			default_image = tmp;
		}
		
		if ((default_image == null) || (default_image.length() <= 0))
			default_image = 
				"http://cdn.last.fm/flatness/catalogue/noimage/1/default_artist_large.png";
		return default_image;
	}

	/**
	 * @param imageUrl
	 * @return o bitmap da imagem
	 */
	private Bitmap urlToImage(String imageUrl) {
	
		LastfmURL myFileUrl = null;
		try {
			myFileUrl = new LastfmURL(imageUrl);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	
		InputStream is = null;
		try {
			is = myFileUrl.openStream();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (LastfmBluetoothUnavailableException e) {
			e.printStackTrace();
		}
	
		return BitmapFactory.decodeStream(is);
	}
}